package com.example.tutorial.java.concurrent.practice.ch6;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author: cph
 * @date: 2022/4/24 14:25
 */
public class InvokeAllThreadTest {

    ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    private class QuoteTask implements Callable<BigDecimal> {

        private Double price;
        private Integer num;

        public QuoteTask(Double price, Integer num) {
            this.price = price;
            this.num = num;
        }

        @Override
        public BigDecimal call() throws Exception {
            Thread.sleep(3000L);
            BigDecimal result = BigDecimal.valueOf(price * num).setScale(2);
            return result;
        }
    }

    public void getRankedTravelQuotes() throws InterruptedException, ExecutionException, TimeoutException {
        List<BigDecimal> totalPriceList = new ArrayList<>();
        List<QuoteTask> tasks = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            tasks.add(new QuoteTask(200.0, i));
        }

        // 使用invokeAll提交批量限时任务，预期10s内所有任务都执行完，未执行完的任务会被自动取消
        List<Future<BigDecimal>> futures = executor.invokeAll(tasks, 10, TimeUnit.SECONDS);
        for (Future<BigDecimal> future : futures) {
            totalPriceList.add(future.get());
        }

        // 使用invokeAny提交批量限时任务，预期10s内会有一任务返回，未执行完的任务会被自动取消
//        BigDecimal result = executor.invokeAny(tasks, 10, TimeUnit.SECONDS);
//        totalPriceList.add(result);

        totalPriceList.forEach((t) -> System.out.println(t));
        executor.shutdown();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        InvokeAllThreadTest t = new InvokeAllThreadTest();
        t.getRankedTravelQuotes();
    }

}
